package my.SimulatorGUI1;
import my.util.Debug;
import my.util.Handler;

public class Timer implements Runnable{
    private Thread runner;
    private String message;         //the message sent
    private int delay;             //interval between messages
    private Handler callBack;        //the object that handles the message
    private boolean gag;            //toggles sending of message every interval
    private boolean alive;
    
    public Timer(String message, int delay, Handler callBack){
        init(message, delay, callBack);
        runner = new Thread(this);
        runner.start();
    }
    
    public void init(String message, int delay, Handler callBack){
        this.message = message;
        this.delay = delay*1000; // change seconds to milliseconds
        this.callBack = callBack;
        gag = false;  
        alive = true;
    }
    
    public void toggleGag(){
        gag = !gag;
    }
    
    public void gag(){
        gag = true;
    }
    public void ungag(){
        gag = false;
    }
    
    public void die(){
        alive = false; // Timer will die on the next loop through run()
    }
    public void run(){
        while(alive){
            try {
                Thread.sleep(delay);
            }
            catch(InterruptedException e){
                ;  // do nothing
            }
            if (!gag)  // we are allowed to send the message
                callBack.handle(message);
        }
    }    
}
